import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
import { Reflector } from '@nestjs/core';

@Injectable()
export class RoleGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    console.log("经过守卫");
    const roles = this.reflector.get<string[]>('role', context.getHandler());   // 拿元数据的内容
    console.log("roles",roles);
    const req = context.switchToHttp().getRequest();   // 获取请求头中的user信息
    console.log(req.user.role);
    if(roles.includes(req.user.role)) {
      return true;
    } else {
      return false;
    }
    // return true;
  }
}
